//加载依赖库
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//创建express实例
var app = express();

//配置模版引擎 - 这里是art-template
var template = require('art-template');
app.engine('html', template.__express);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));

//定义icon图标
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

// 定义日志和输出级别
app.use(logger('dev'));

// 定义数据解析器
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

// 定义cookie解析器
app.use(cookieParser());

// 定义静态文件目录
app.use(express.static(path.join(__dirname, 'public')));

//init执行完毕后加载路由
require('./init.js')
    .init(function () {

        return new Promise((O, X)=> {
            //加载路由控制
            app.use('/api/course/', require('./routes/course'));
            app.use('/api/admin/course/', require('./routes/admin_course'));

            app.use('/api/user/', require('./routes/user'));
            app.use('/api/admin/user/', require('./routes/admin_user'));

            app.use('/api/homework/', require('./routes/homework'));
            app.use('/api/admin/homework/', require('./routes/admin_homework'));

            app.use('/api/notice/', require('./routes/notice'));
            app.use('/api/admin/notice/', require('./routes/admin_notice'));

            app.use('/file/', require('./routes/file'));

            //404错误处理
            app.use(function (req, res, next) {
                var err = new Error('Not Found');
                err.status = 404;
                next(err);
            });

            if (app.get('env') === 'development') {
                app.use(function (err, req, res, next) {
                    res.status(err.status || 500);
                    console.log(err);
                    res.json({
                        code: 9999,
                        message: err.message,
                        error: {}
                    });
                });
            }

            app.use(function (err, req, res, next) {
                res.status(err.status || 500);
                res.json({
                    code: 9999,
                    message: err.message,
                    error: {}
                });
            });

            O();
        })

    });


module.exports = app;
